package com.hadluo.qq.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.hadluo.qq.server.entity.User;
import com.hadluo.qq.server.service.UserService;
import com.hadluo.qq.server.vo.RegisterRequest;
import com.hadluo.qq.server.vo.LoginRequest;
import com.hadluo.qq.server.vo.Result;
import com.hadluo.qq.server.websocket.ChatWebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.Optional;

/**
 * 用户控制器
 * @author hadluo
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册接口
     * @param request 注册请求参数
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseEntity<Result<?>> register(@RequestBody @Validated RegisterRequest request) {
        try {
            // 生成5位数字QQ号
            String qqNumber;
            do {
                qqNumber = String.format("%05d", new Random().nextInt(100000));
            } while (userService.existsByQqNumber(qqNumber));

            // 创建新用户
            User user = new User();
            user.setQqNumber(qqNumber);
            user.setNickname(request.getNickname());
            user.setPassword(request.getPassword()); // 实际应用中应该对密码进行加密
            user.setGender(request.getGender());
            user.setAvatar(request.getAvatar());
            user.setSignature(request.getSignature());

            // 保存用户
            userService.save(user);

            // 创建包含QQ号的响应数据
            JSONObject data = new JSONObject();
            data.put("qqNumber", qqNumber);
            // 返回成功信息，包含生成的QQ号
            return ResponseEntity.ok(Result.success("注册成功", data));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error("注册失败：" + e.getMessage()));
        }
    }

    /**
     * 用户登录接口
     * @param request 登录请求参数
     * @return 登录结果
     */
    @Autowired
    private ChatWebSocket chatWebSocket;

    @PostMapping("/login")
    public ResponseEntity<Result<?>> login(@RequestBody @Validated LoginRequest request) {
        System.out.println("收到登录请求，参数：" + request);
        try {
            // 检查用户是否已经在线
            if (ChatWebSocket.isUserOnline(request.getQqNumber())) {
                return ResponseEntity.ok(Result.error("该账号已在其他设备登录"));
            }

            // 根据QQ号查找用户
            User user = userService.findByQqNumber(request.getQqNumber())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            // 验证密码
            if (!user.getPassword().equals(request.getPassword())) {
                throw new RuntimeException("密码错误");
            }

            // 更新最后登录时间
            user.setLastLogin(new Date());
            userService.save(user);

            // 创建登录响应数据
            JSONObject data = new JSONObject();
            data.put("qqNumber", user.getQqNumber());
            data.put("nickname", user.getNickname());
            data.put("gender", user.getGender());
            data.put("avatar", user.getAvatar());
            data.put("signature", user.getSignature());

            ResponseEntity<Result<?>> response = ResponseEntity.ok(Result.success("登录成功", data));
            System.out.println("登录成功，返回数据：" + data);
            return response;
        } catch (Exception e) {
            System.out.println("登录失败，错误信息：" + e.getMessage());
            return ResponseEntity.ok(Result.error("登录失败：" + e.getMessage()));
        }
    }

    /**
     * 更新用户个人资料
     * @param request 更新请求参数
     * @return 更新结果
     */
    @PostMapping("/update")
    public ResponseEntity<Result<?>> updateProfile(@RequestBody Map<String, Object> request) {
        try {
            String qqNumber = (String) request.get("qqNumber");
            String nickname = (String) request.get("nickname");
            String avatar = (String) request.get("avatar");

            // 根据QQ号查找用户
            User user = userService.findByQqNumber(qqNumber)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            // 更新用户信息
            user.setNickname(nickname);
            user.setAvatar(avatar);
            userService.save(user);

            return ResponseEntity.ok(Result.success("更新成功"));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error("更新失败：" + e.getMessage()));
        }
    }
    /**
     * 获取用户信息接口
     * @param qqNumber 用户QQ号
     * @return 用户信息
     */
    @GetMapping("/info")
    public ResponseEntity<Result<?>> getUserInfo(@RequestParam String qqNumber) {
        try {
            // 根据QQ号查找用户
            User user = userService.findByQqNumber(qqNumber)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            // 创建用户信息响应数据
            JSONObject data = new JSONObject();
            data.put("qqNumber", user.getQqNumber());
            data.put("nickname", user.getNickname());
            data.put("gender", user.getGender());
            data.put("avatar", user.getAvatar());
            data.put("signature", user.getSignature());
            data.put("status", ChatWebSocket.isUserOnline(user.getQqNumber()) ? "online" : "offline");

            return ResponseEntity.ok(Result.success(data));
        } catch (Exception e) {
            return ResponseEntity.ok(Result.error("获取用户信息失败：" + e.getMessage()));
        }
    }
}